var windowName = "addPics";
var Page, filter, textCover, picResize, picTool;
// var MatterLog = new List()


$(function () {
    // var copperElement = $('#tailoringImg');
    var pu = new PicUp()
    // picTool = new  PicTool();

    console.log("index page is OK");
    filter = new Filter();
    textCover = new TextCover();
    Page = createVM("#Page", {
        //页面数据
        id: 0,
        title: "打印列表",
        picsOrg: {},
        pics: [],
        picsUpload: [],
        style: "style",//批量处理 滤镜
        picsNum: {},
        picsStyle: {},
        picsMark: {},//单独定制的水印

        //统一水印
        markAllShow: false,
        picsMarkText: "",
        picsMarkPos: 0,
        picsMarkRote: 3,

        orderTitle: "",
        total: "-",
        num_total: 10,
        num_upload: 0,
        picW: 0,
        picH: 0,

        num_cur: 0,
        canvasWidth: 0,
        canvasHeight: 0,
        tab: 0,
        subTab: 0,


        loadingText: "",
        showLoading: false,

        styles: [],//统一板式
        styleIndex: -1,

        //单个编辑
        curPic: "",
        curIndex: "",
        editShow: false,
        corpShow: false,


        //单独水印
        markShow: false,
        picMarkText: "",
        picMarkPos: 0,
        picMarkRote: 3,

        //单独滤镜//todo
        filterShow: false,
        picStyle:"",

        picsCheck: [],
        picsAllCheck: [],
        page: 0,
        checkShow: false,
    }, {
        //页面方法

        /**
         * 生命周期函数--监听页面加载
         */
        onLoad: function (options) {
            let _this = this

            picResize = new PicResize("select", this, function (org, resized,waiting) {
                console.log(org);
                console.log(resized);
                var orgLen = 0;for (var i in org) {orgLen++}
                var resizedLen = 0;for (var i in org) {resizedLen++}
                console.log("org;" + waiting.length)
                console.log("resized;" + resizedLen)


                let loadingText = '，正在压缩' + waiting.length + "/" + resizedLen
                _this.setData({loadingText})
                if (waiting.length === resizedLen) {
                    let pics = _this.pics
                    let picsOrg = _this.picsOrg
                    loadingText = ""
                    pics = resized.concat(pics)
                    // pics = resized
                    // picsOrg = org.concat(picsOrg)
                    for (var i in org) {picsOrg[i] = org[i]}
                    // for (var i in resized) {pics[i] = resized[i]}


                    let num_cur = pics.length
                    _this.setData({pics, num_cur, loadingText,picsOrg})

                    _this.recountPic()
                }

            })
            this.id = getUrlData("id")
            getOrderInfo(this)
            // getChoices(this)

            // copperElement.cropper('replace', "/assets/images/addpic.png", false);
        },
        submit: function () {
            let _this = this
            let id = this.id
            let pics = this.pics
            let style = this.style
            let picsNum = JSON.stringify(this.picsNum)
            let picsStyle = JSON.stringify(this.picsStyle)
            let picsMark = JSON.stringify(this.picsMark)
            console.log(this.picsStyle);
            console.log(this.picsMark);

            picsNum = this.picsNum
            picsStyle = this.picsStyle
            picsMark = this.picsMark

            let text = this.picsMarkText
            let picsMarkPos = this.picsMarkPos
            let picsMarkRote = this.picsMarkRote

            apiPost("/po/order/create/2", {
                id,
                pics,
                style,
                picsNum,
                picsStyle,
                text,
                picsMark,
                picsMarkPos,
                picsMarkRote
            }, function (res) {

                checkPics(_this)

                // goto("/pic/Page/Wap/check.html?id=" + id)
            })
        },

        corp: function (index) {

            this.corpShow = true;
            // this.textList = isTrue(this.watermarks[this.curIndex])?this.watermarks[this.curIndex]:[]
            //
            // if (isTrue(this.filters[this.curIndex])) {
            //     filter.setData(this.filters[this.curIndex]);
            // }else {
            //     filter.reset()
            // }
            // this.style = filter.getStyle()
        },


        closeEdit: function () {
            this.editShow = false;
            //保存此次编辑的数据
            //-1保存水印,保存滤镜
            // this.watermarks[this.curIndex] = this.textList
            // this.filters[this.curIndex] = filter.getData()

            //-2清空数据
            // this.textList = []
            this.onShow()
        },
        endEdit: function () {
            this.editShow = false;
            //保存此次编辑的数据
            //-1保存水印,保存滤镜
            // this.watermarks[this.curIndex] = this.textList
            // this.filters[this.curIndex] = filter.getData()

            //-2清空数据
            // this.textList = []
            // this.onShow()
        }
        , showEdit: function (index) {
            // this.corpShow = true;
            console.log(this);
            console.log(index);
            console.log(this.pics[index]);
            console.log(this.pics);
            console.log(this.picsOrg);
            let pic = this.pics[index]
            this.editShow = true;
            this.curPic = pic;
            this.curIndex = index;
            //图片裁剪
            // $('#tailoringImg').cropper('replace', pic,false);//默认false，适应高度，不失真

            $('#tailoringImg').cropper('replace', this.picsOrg[pic], false);
            //cropper图片裁剪
            // copperElement = $('#curPic');
            console.log(this.picW / this.picH);
            $('#tailoringImg').cropper({
                aspectRatio: this.picW / this.picH,//默认比例
                preview: '.previewImg',//预览视图
                guides: false,  //裁剪框的虚线(九宫格)
                autoCropArea: 0.9,  //0-1之间的数值，定义自动剪裁区域的大小，默认0.8
                movable: false, //是否允许移动图片
                dragCrop: false,  //是否允许移除当前的剪裁框，并通过拖动来新建一个剪裁框区域
                // movable: true,  //是否允许移动剪裁框
                resizable: false,  //是否允许改变裁剪框的大小
                zoomable: true,  //是否允许缩放图片大小
                mouseWheelZoom: false,  //是否允许通过鼠标滚轮来缩放图片
                touchDragZoom: true,  //是否允许通过触摸移动来缩放图片
                rotatable: true,  //是否允许旋转图片
                crop: function (e) {
                    // 输出结果数据裁剪图像。
                    console.log("done");
                }
            });
        }

        ,showFilterMark: function () {

            this.filterShow = this.filterShow == false ? true : false

            // this.editShow = false;
            // //保存此次编辑的数据
            // //-1保存水印,保存滤镜
            // this.watermarks[this.curIndex] = this.textList
            // this.filters[this.curIndex] = filter.getData()
            //
            // //-2清空数据
            // this.textList = []
        }
        , showEditMark: function (e) {
            console.log(e);
            // this.setData({ tab: this.tab == 0 ? 1 : 0 })
            this.markShow = this.markShow == false ? true : false
        }
        , showAllEditMark: function (e) {
            console.log(e);
            // this.setData({ tab: this.tab == 0 ? 1 : 0 })
            this.markAllShow = this.markAllShow == false ? true : false
        }

        ,onShow: function () {
            this.editShow = false
            // let orgPic = wx.getStorageSync("picUrlToEdit")
            // let editPic = wx.getStorageSync("editPic")
            // let editPicStyle = wx.getStorageSync("editPicStyle")
            // let editPicMark = wx.getStorageSync("editPicMark")
            // console.log(orgPic)
            // console.log(typeof editPic)
            // console.log(editPic)
            // console.log(editPicStyle)

            //删除原有的数据
            console.log(this.pics)
            console.log(this.picsNum)
            console.log(this.picsStyle)
            // if (editPic == "" && editPicStyle == "") {
            //     return
            // }


            // let pics = com.arrayDelValue(this.pics, orgPic)
            let pics = this.pics
            let picOrg = pics[this.curIndex];
            pics[this.curIndex] = this.curPic
            this.pics = pics
            // pics.push(editPic)

            //修改图片数量的key
            let curNum = this.picsNum[picOrg]
            let picsNum = objDelValue(this.picsNum, picOrg)
            picsNum[this.curPic] = curNum


            //获取到的图片样式
            let picsStyle = objDelValue(this.picsStyle,picOrg)
            picsStyle[this.curPic] = this.picStyle


            //获取到的水印样式
            // let picsMark = this.picsMark
            let picsMark = objDelValue(this.picsMark,picOrg)
            picsMark[this.curPic] = this.picMarkText

            // console.log(pics)
            // console.log(picsNum)
            console.log({ pics, picsStyle, picsMark})
            this.setData({picsNum, pics, picsStyle, picsMark})

            // wx.removeStorage({key: "editPic"})
            // wx.removeStorage({key: "editPicStyle"})

        },

        del: function (index) {
            // let data = com.getViewData(e)
            // console.log(data)

            let picsNum = objDelIndex(this.picsNum, this.pics[index])

            let pics = arrayDelIndex(this.pics, index)
            let num_cur = this.num_cur - 1

            // let picsNum = com.arrayDelIndex(this.picsNum, data.index)


            this.setData({pics, num_cur, picsNum})

            this.recountPic()
        },

        picNumRed: function (index,i) {
            console.log(index)
            let picsNum = this.picsNum
            picsNum[index] = picsNum[index] == undefined ? 1 : picsNum[index] - 1
            if (picsNum[index] < 1) {
                picsNum[index] = 1
            }
            $("#num_" + i).val(picsNum[index])
            this.$set(picsNum, index, picsNum[index])
            this.recountPic()
        },
        picNumAdd: function (index,i) {
            let picsNum = this.picsNum
            console.log('-----------')
            console.log(index)
            console.log('-----------')
            picsNum[index] = picsNum[index] == undefined ? 1 : picsNum[index] + 1


            console.log('-----------')
            console.log(this.picsNum)
            console.log('-----------')
            console.log(picsNum.length)
            // this.picsNum = picsNum
            // this.setData({picsNum})

            $("#num_" + i).val(picsNum[index])
            this.$set(this.picsNum, index, picsNum[index])
            this.recountPic()
        },
        picNumSet: function (index,i,_this) {
            let val = _this.val() * 1

            // console.log(e)
            let picsNum = this.picsNum
            picsNum[index] = val
            if (picsNum[index] < 1) {
                picsNum[index] = 1
            }
            this.setData({picsNum})
            this.recountPic()
        },

        /**
         * 用户点击右上角分享
         */
        addPic: function () {
            let _this = this
            picResize.reset()
            let num = this.num_total - this.num_cur

            // if (num < 1) {
            //     wx.showToast({
            //         title: '已达到上限',
            //     })
            //     return false;
            // }
            if (this.picW == 0) {
                wx.showToast({
                    title: '数据加载中',
                })
                return false;
            }
            // picResize.setSize(this.picW, this.picH)
            // picResize.pickAndResize(_this,function(org,resized){
            //     console.log("org;" + org.length)
            //     console.log("resized;" + resized.length)
            //     let loadingText = '，正在压缩' + resized.length + "/" + org.length
            //     _this.setData({ loadingText })
            //     if (org.length === resized.length){
            //         let pics = _this.pics
            //         loadingText = ""
            //         pics = resized.concat(pics)
            //         let num_cur = pics.length
            //         _this.setData({ pics, num_cur, loadingText})
            //
            //     }
            // }, num)
        },
        recountPic: function () {
            console.log(this);
            let picsNum = this.picsNum;
            let total = 0
            this.pics.map(function (data) {
                if (picsNum[data] != undefined) {
                    total += picsNum[data] * 1
                } else {
                    total += 1
                }
            })
            this.setData({total})

            //更新输入框数据
            for(var i in this.pics){
                var pic = this.pics[i];
                var num = 1;
                if (this.picsNum[pic] != undefined) {
                    num = this.picsNum[pic]
                }
                $("#num_" + i).val(num)

            }


        }
        , next: function () {

            //检查总打印份数是不是9的倍数
            this.recountPic()
            console.log(this.total)
            console.log(this.total)
            // if (this.total % 9 != 0) {
            //     showToast('亲！这边需要您提交的打印份数要为9的倍数才可以呢。')
            //     let showLoading = false
            //     this.setData({showLoading})
            //     return;
            // }
            this.submit();
        }
        , upload: function () {
            let _this = this
            let showLoading = true
            _this.setData({showLoading})

            if (this.pics.length === 0) {
                wx.showToast({
                    title: '请先添加图片',
                    icon: 'loading',
                })
                let showLoading = false
                _this.setData({showLoading})
                return;
            }

            if (this.pics.length > this.picsUpload.length) {
                let curPic = this.pics[this.picsUpload.length];
                api.upload("/MyWebPicUpload", curPic, 'Filedata', {name: "Filedata"}, function (res) {

                    //回调后网络地址放到已上传
                    //还要修改图片数据问题
                    let picsNum = _this.picsNum
                    picsNum[res.d] = picsNum[curPic]
                    picsNum = com.objDelIndex(picsNum, curPic)


                    console.log(res)
                    if (res.d == "") {
                        return
                    }
                    _this.picsUpload.push(res.d)

                    let picsStyle = _this.picsStyle
                    picsStyle[res.d] = picsStyle[curPic]
                    picsStyle = com.objDelIndex(picsStyle, curPic)

                    let picsMark = _this.picsMark
                    picsMark[res.d] = picsMark[curPic]
                    picsMark = com.objDelIndex(picsMark, curPic)

                    let text = _this.picsMarkText
                    _this.setData({num_upload: _this.picsUpload.length, picsNum, picsStyle, picsMark, text})
                    _this.upload()
                })
            } else {

                let showLoading = false
                _this.setData({showLoading})
                this.submit()
            }
        },
        setSpace: function (index) {
            // let data = com.getViewData(e)
            // let index = data.index
            let style = this.styles[index]

            let styleIndex = index
            this.setData({styleIndex})
            console.log(style)
            if (style.isCut == 1) {
                picResize.setCut(true)
            } else {
                picResize.setCut(false)
            }

            let x = this.picW / this.paperData[0]
            picResize.setSpace(style.spaceLeft * x, style.spaceRight * x, style.spaceTop * x, style.spaceBottom * x)
        }
        //水印相关功能
        , setMarkText: function (e) {
            let picsMarkText = e.detail.value
            this.setData({picsMarkText})
            wx.setStorage({
                key: 'picsMarkText',
                data: picsMarkText,
            })
        }
        , setMarkPos: function (index) {
            // let data = com.getViewData(e)
            // let index = data.index;
            // let picsMarkPos = index
            this.setData({picsMarkPos: index})
        }
        , setMarkRote: function (index) {
            // let data = com.getViewData(e)
            // let index = data.index;
            // let picsMarkRote = index
            this.setData({picsMarkRote: index})
        }

        , corpRoute: function () {
            $('#tailoringImg').cropper("rotate", 45)

        }
        , corpSave: function () {
            let _this = this;
            if ($("#tailoringImg").attr("src") == null ){
                return false;
            }else{
                var cas = $('#tailoringImg').cropper('getCroppedCanvas');//获取被裁剪后的canvas
                var base64url = cas.toDataURL('image/png'); //转换为base64地址形式
                picResize.dealWithOne(this,base64url,function (org, resized) {
                    console.log(org);
                    console.log(resized);
                    _this.curPic = resized[0]

                    _this.corpShow = false;
                })

                // $("#finalImg").prop("src",base64url);//显示为图片的形式

                //关闭裁剪框
                // closeTailor();

            }


        }

        , setOneMarkPos: function (index) {
            // let data = com.getViewData(e)
            // let index = data.index;
            let picMarkPos = index
            let picMarkText = "mark pos" + picMarkPos + " rote" + this.picMarkRote + " cf op8"
            this.setData({ picMarkPos,picMarkText })


        }
        , setOneMarkRote: function (index) {
            // let data = com.getViewData(e)
            // let index = data.index;
            let picMarkRote = index
            let picMarkText = "mark pos" + this.picMarkPos + " rote" + picMarkRote + " cf op8"
            this.setData({ picMarkRote,picMarkText })
        }


        //滤镜相关
        , filterReset: function () {
            filter.reset()
            this.setData({ picStyle: filter.getStyle() })
        },
        setBlur: function (num) {
            filter.setBlur(2)
            // this.filters[this.curIndex] = filter.getStyle();
            this.setData({ picStyle: filter.getStyle() })
        },
        setContrast: function (num) {
            filter.setContrast(160)
            // this.filters[this.curIndex] = this.style = filter.getStyle();
            this.setData({ picStyle: filter.getStyle() })
        },
        setHueRotate: function (num) {
            filter.setHueRotate(180)
            // this.filters[this.curIndex] = filter.getStyle();
            this.setData({ picStyle: filter.getStyle() })
        },
        setBrightness: function (num) {
            filter.setBrightness(120)
            // this.filters[this.curIndex] = filter.getStyle();
            this.setData({ picStyle: filter.getStyle() })
        },
        setOpacity: function (num) {
            filter.setOpacity(50)
            // this.filters[this.curIndex] = filter.getStyle();
            this.setData({ picStyle: filter.getStyle() })
        },
        setGrayScale: function (num) {
            filter.setGrayScale(100)
            console.log(filter.getStyle())
            this.setData({ picStyle: filter.getStyle() })
            // this.filters[this.curIndex] = filter.getStyle();
            // this.setData({ picStyle: filter.getStyle() })
        },
        setSaturate: function (num) {
            filter.setSaturate(360)
            // this.filters[this.curIndex] = filter.getStyle();
            this.setData({ picStyle: filter.getStyle() })
        },
        setSepia: function (num) {
            filter.setSepia(100)
            // this.filters[this.curIndex] = filter.getStyle();
            this.setData({ picStyle: filter.getStyle() })
        },
        setInvert: function (num) {
            filter.setInvert(100)
            // this.filters[this.curIndex] = filter.getStyle();
            this.setData({ picStyle: filter.getStyle() })
        },

        next2: function (e) {

        let id = this.id
        goto("/pic/Page/Wap/selectBack.html?id=" + id)
        },
        goback: function (e) {
            // let id = this.id
            // goto("/pic/Page/Wap/selectStyle.html?id=" + id)
            // history.go(-1)
            this.checkShow = false;
    },
        showMore: function () {


            let _this = this;
            let picsCheck = _this.picsCheck

            let find = 0;
            _this.picsAllCheck.map(function (data, index) {
                if (index >= _this.page * 9 && index < (_this.page + 1) * 9) {
                    find = 1;
                    picsCheck.push(data)
                }
            })
            if (find === 1) {
                // showToast('加载中...')
            } else {
                showToast('已全部加载')
            }
            let page = _this.page + 1;
            _this.setData({picsCheck, page})
        }
    })

    Page.onLoad()

})

function getData(_this) {
    apiGet("/app/car/log/add", {}, function (res) {
        _this.types = res.d.type
        _this.cars = res.d.cars
        _this.en = res.d.en
        _this.sites = res.d.sites
    })
}


function getOrderInfo(_this) {
    let id = _this.id
    apiGet("/po/order/create/99", {id}, function (res) {
        let num_total = res.d.num == 0 ? 99999 : res.d.num;
        let picW = res.d.picw
        let picH = res.d.pich
        let paperData = res.d.paperData
        let orderTitle = res.d.title
        _this.num_total = num_total
        _this.picW = picW
        _this.picH = picH
        _this.orderTitle = orderTitle
        _this.paperData = paperData
        picResize.setSize(_this.picW, _this.picH)
        // _this.setData({ num_total, picW, picH, orderTitle, paperData})
        // getChoices(_this)

        // getChoices(_this)

        let style = res.d.space

        console.log(style)
        if (style.isCut == 1) {
            picResize.setCut(true)
        } else {
            picResize.setCut(false)
        }

        let x = _this.picW / _this.paperData[0]
        picResize.setSpace(style.spaceLeft * x, style.spaceRight * x, style.spaceTop * x, style.spaceBottom * x)


    })
}

function getChoices(_this) {
    apiGet("/po/get/choices", {}, function (res) {
        // let styles = res.d.style
        // _this.styles = styles
        //

        let styles = res.d.style
        _this.setData({styles})


        //设置默认
        // let data = com.getViewData(e)
        let index = 0
        let style = styles[index]

        let styleIndex = index
        _this.setData({styleIndex})
        console.log(style)
        if (style.isCut == 1) {
            picResize.setCut(true)
        } else {
            picResize.setCut(false)
        }

        let x = _this.picW / _this.paperData[0]
        picResize.setSpace(style.spaceLeft * x, style.spaceRight * x, style.spaceTop * x, style.spaceBottom * x)
    })
}


/**
 * 将以base64的图片url数据转换为Blob 可以直接上传文件
 * @param urlData
 *            用url方式表示的base64图片数据
 */
function convertBase64UrlToBlob(urlData) {
    var bytes = window.atob(urlData.split(',')[1]);        //去掉url的头，并转换为byte
    //处理异常,将ascii码小于0的转换为大于0
    var ab = new ArrayBuffer(bytes.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
    }
    return new Blob([ab], {type: 'image/png'});
}

function upLoadBase64Pic(pic) {
    var formData = new FormData();   //这里连带form里的其他参数也一起提交了,如果不需要提交其他参数可以直接FormData无参数的构造函数
    //convertBase64UrlToBlob函数是将base64编码转换为Blob
    formData.append("Filedata", convertBase64UrlToBlob(pic.base64));  //append函数的第一个参数是后台获取数据的参数名,和html标签的input的name属性功能相同
    //ajax提交form表单
    $.ajax({
        url: '/MyWebPicUpload',
        type: "POST",
        data: formData,
        dataType: "json",
        processData: false,         // 告诉jQuery不要去处理发送的数据
        contentType: false,        // 告诉jQuery不要去设置Content-Type请求头
        success: function (data) {
            //todo
        },
        xhr: function () {
            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener("progress", function (evt) {
                if (evt.lengthComputable) {
                    var percentComplete = Math.round(evt.loaded * 100 / evt.total);
                    console.log("正在提交." + percentComplete.toString() + '%');
                }
            }, false);
            return xhr;
        }

    });
}



function checkPics(_this) {
    _this.checkShow = true;
    let id = _this.id
    apiGet("/po/order/create/99", {id}, function (res) {
        let picsCheck = []
        let picsAllCheck = res.d.pics
        res.d.pics.map(function (data, index) {
            console.log(data)
            console.log(index)
            if (index >= _this.page * 9 && index < (_this.page + 1) * 9) {

                picsCheck.push(data)
            }
        })
        let page = 1;
        _this.setData({picsAllCheck, picsCheck, page})
    })
}
